﻿using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Security;
using IrisMembership.DomainClasses;
using Newtonsoft.Json;

namespace IrisMembership.Web.Authentication
{
    public class IrisIdentity : IIdentity
    {
        public IrisIdentity(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                AsGuest();
                return;
            }

            var data = JsonConvert.DeserializeObject<IrisCookie>(ticket.UserData);

            if (data == null)
            {
                AsGuest();
                return;
            }

            UserId = data.UserId;
            UserName = data.UserName;
            Name = data.Name;
        }

        public IrisIdentity(UserTicket userTicket)
        {
            if (userTicket == null)
            {
                AsGuest();
                return;
            }

            UserName = userTicket.UserName;
            Name = userTicket.Name;
        }

        private void AsGuest()
        {
            Name = "Guest";
            Role = "guest";
        }

        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Name { get; set; }
        public string Role { get; set; }

        #region IIdentity Members

        public string AuthenticationType
        {
            get { return "IrisForms"; }
        }

        public bool IsAuthenticated
        {
            get { return !string.IsNullOrEmpty(UserName); }
        }

        #endregion
    }
}